package com.github.ybq.core.style;

import com.github.ybq.core.sprite.Sprite;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.BlendMode;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Rect;

public class DoubleBounce extends Sprite {

    private int num = 2;
    private float[] radius = new float[]{0f,0f};

    private AnimatorValue mAnimatorValue;


    public DoubleBounce() {
        super();

        initAnimator();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setStyle(Paint.Style.FILL_STYLE);
        mPaint.setStrokeWidth(getPaintStrokeWidth());
        mPaint.setAlpha(0.6f);
//        mPaint.setBlendMode(BlendMode.MULTIPLY);
 
        if (getRect() != null) {
            Rect bounds = clipSquare(getRect(),50);
            float maxRadius = bounds.getWidth() / 2f;
            for (int i = 0; i < num; i++) {
                float mRadiusValue = radius[i] * maxRadius;
                canvas.drawCircle(bounds.getCenterX(), bounds.getCenterY(), mRadiusValue, mPaint);
            }

            startAnimator();
        }
    }
    @Override
    public void startAnimator(){
        if (mAnimatorValue != null){
            if (!mAnimatorValue.isRunning()){
                mAnimatorValue.start();
            }
        }
    }
    @Override
    public boolean isRunning() {
        if (mAnimatorValue != null){
            return mAnimatorValue.isRunning();
        }
        return super.isRunning();
    }
    private boolean isLoop = false;

    private void initAnimator(){
        if (mAnimatorValue == null){
            mAnimatorValue = new AnimatorValue();
            mAnimatorValue.setLoopedCount(Animator.INFINITE);
            mAnimatorValue.setDuration(2000);
            mAnimatorValue.setCurveType(Animator.CurveType.LINEAR);
            mAnimatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
                @Override
                public void onUpdate(AnimatorValue animatorValue, float v) {
                    if(v > 0.5f) {
                        isLoop = true;
                    }
                    if (v < 0.5){
                        radius[0] = v * 2;
                        if(isLoop){
                            radius[1] = 1 - v* 2;
                        }else{
                            radius[1] = 0;
                        }
                    }else {
                        radius[0] = (1 - v) * 2;
                        radius[1] = (v - 0.5f) * 2;
                    }
                    if (getComponent() != null){
                        getComponent().invalidate();
                    }
                }
            });
        }
    }
    @Override
    public void stopAnimator(){
        if (mAnimatorValue != null){
            if (mAnimatorValue.isRunning()){
                mAnimatorValue.stop();
            }
        }
    }
}

